//
//  LZChangeComments.m
//  LZSpamCode
//
//  Created by ZengLiZhi on 2024/6/26.
//

#import "LZChangeComments.h"
#import "LZSpamCodeManager.h"
#import "LZFileManager.h"

@implementation LZChangeComments

+ (void)start{
    
    @autoreleasepool {
        [self deleteComments:[LZSpamCodeManager shareInstance].gSourceCodeDir ignoreDirNames:[LZSpamCodeManager shareInstance].gIgnoreDirNames];
    }
    printf("删除注释和空行完成\n");
}

#pragma mark - 删除注释
+ (void)deleteComments:(NSString *)directory  ignoreDirNames:(NSArray<NSString *> *)ignoreDirNames {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray<NSString *> *files = [fm contentsOfDirectoryAtPath:directory error:nil];
    BOOL isDirectory;
    for (NSString *fileName in files) {
        if ([ignoreDirNames containsObject:fileName]) continue;
        NSString *filePath = [directory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
            [self deleteComments:filePath ignoreDirNames:ignoreDirNames];
            continue;
        }
        if (![fileName hasSuffix:@".h"] && ![fileName hasSuffix:@".m"] && ![fileName hasSuffix:@".mm"] && ![fileName hasSuffix:@".swift"]) continue;
        NSMutableString *fileContent = [NSMutableString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        [LZFileManager regularReplacement:fileContent regularExpression:@"([^\":/])//.*" newString:@"\\1"];
        [LZFileManager regularReplacement:fileContent regularExpression:@"^//.*" newString:@""];
        [LZFileManager regularReplacement:fileContent regularExpression:@"/\\*{1,2}[\\s\\S]*?\\*/" newString:@""];
        [LZFileManager regularReplacement:fileContent regularExpression:@"^\\s*\\n" newString:@""];
        [fileContent writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

@end
